import 'package:get/get.dart';
import 'package:grocery_app_demo/api/entity/login_res_entity.dart';
import 'package:grocery_app_demo/api/scm_api.dart';
import 'package:grocery_app_demo/core/utils/global.dart';
import 'package:grocery_app_demo/routes/app_routes.dart';

class SplashController extends GetxController {
  @override
  void onReady() {
    super.onReady();
    refreshToken();
    Future.delayed(const Duration(seconds: 2), () {
      Get.toNamed(AppRoutes.purchase);
    });
  }

  refreshToken() {
    var tokenExpiresTime = Global.getInt(SpKey.tokenExpiresTime);
    var refreshToken = Global.getString(SpKey.refreshToken);
    if (tokenExpiresTime == null || refreshToken == null) {
      return;
    }
    if (DateTime.now().millisecondsSinceEpoch >= tokenExpiresTime) {
      ScmApi().post<LoginResEntity>(ScmApi.refreshToken,
          queryParameters: {'refreshToken': refreshToken}).then((value) {
        Global.token = value.accessToken;
        Global.setString(SpKey.refreshToken, value.refreshToken);
        Global.setInt(SpKey.tokenExpiresTime, value.expiresTime);
      }).onError((error, stackTrace) {
        Global.remove(SpKey.token);
        Global.remove(SpKey.refreshToken);
        Global.remove(SpKey.tokenExpiresTime);
      });
    }
  }
}
